package com.tuling.jucdemo.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author :tangweiliang
 * @date : 2022/11/17 21:44
 * 未来的你会感谢现在努力的自己
 * <p>
 * 锁超时 立刻失败
 */
@Slf4j
public class ReentrantLockDemo4 {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {
            log.debug("t1启动......");

            try {
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {
                    log.debug("等待1s后获取锁失败,返回");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }

            try {
                log.debug("t1获得了锁");
            } finally {
                lock.unlock();
            }
        }, "t1");

        lock.lock();
        try{
            log.debug("main线程获取了锁");
            t1.start();
            //先让线程t1执行
            Thread.sleep(2000);
        }finally {
            lock.unlock();
        }

    }
}
